package com.supermap.localization.impl;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Map;

import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.supermap.localization.api.FileReplacer;
import com.supermap.localization.api.LocalizationOperation;
import com.supermap.localization.api.SampleComponent;
import com.supermap.localization.commontypes.SampleInfo;
import com.supermap.localization.util.ConfigsUtil;

public class LocalizationReplacer implements LocalizationOperation {

    private static Logger logger = Logger.getLogger(LocalizationReplacer.class);

    private SampleComponent propSampleComponent;

    private FileReplacer fileReplacer;

    public void setFileReplacer(FileReplacer fileReplacer) {
        this.fileReplacer = fileReplacer;
    }

    public void setPropSampleComponent(SampleComponent propSampleComponent) {
        this.propSampleComponent = propSampleComponent;
    }

    @Override
    public void execute() {
        final Map<String, SampleInfo> sampleInfos = propSampleComponent.readSampleInfos(ConfigsUtil.replaceConfig.getTranslateFilePath());
        logger.info("开始生成FTL，根据翻译后的样本：" + ConfigsUtil.replaceConfig.getTranslateFilePath());
        System.out.println("开始生成FTL，根据翻译后的样本：" + ConfigsUtil.replaceConfig.getTranslateFilePath());
        final Path srcPath = Paths.get(ConfigsUtil.replaceConfig.getSourceDir());
        Path dest = Paths.get(ConfigsUtil.replaceConfig.getDestDir());

        try {
            Files.deleteIfExists(dest);
            Files.createDirectory(dest);
            Files.walkFileTree(srcPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path sourcePath, BasicFileAttributes attrs) throws IOException {
                    String relativeDir = sourcePath.getParent().toString();
                    relativeDir = relativeDir.substring(srcPath.toString().length());
                    String fileName = sourcePath.getFileName().toString();
                    Path destFile = Paths.get(ConfigsUtil.replaceConfig.getDestDir(), relativeDir, fileName);
                    if (Files.notExists(destFile.getParent())) {
                        Files.createDirectories(destFile.getParent());
                    }
                    if (Files.notExists(destFile)) {
                        Files.createFile(destFile);
                    }
                    if (sourcePath.toString().endsWith(".js")) {
                        Files.copy(sourcePath, destFile, StandardCopyOption.REPLACE_EXISTING);
                        return FileVisitResult.CONTINUE;
                    }
                    if (StringUtils.isNotEmpty(ConfigsUtil.extractConfig.getFileSuffix())
                            && !StringUtils.contains(sourcePath.getFileName().toString(), ConfigsUtil.extractConfig.getFileSuffix())) {
                        Path targetFile = Paths.get(ConfigsUtil.replaceConfig.getDestDir(), relativeDir, fileName);
                        Files.copy(sourcePath, targetFile, StandardCopyOption.REPLACE_EXISTING);
                        return FileVisitResult.CONTINUE;
                    }
                    if (StringUtils.isNotEmpty(ConfigsUtil.replaceConfig.getSuffix()) && StringUtils.isNotEmpty(ConfigsUtil.replaceConfig.getReplaceSuffix())) {
                        Files.delete(destFile);
                        fileName = fileName.replace(ConfigsUtil.replaceConfig.getSuffix(), ConfigsUtil.replaceConfig.getReplaceSuffix());
                        destFile = Paths.get(ConfigsUtil.replaceConfig.getDestDir(), relativeDir, fileName);
                        if (Files.notExists(destFile)) {
                            Files.createFile(destFile);
                        }
                    }
                    BufferedWriter bw = null;
                    try {
                        bw = Files.newBufferedWriter(destFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
                        String destFileContent = fileReplacer.replace(sourcePath, sampleInfos);
                        bw.write(destFileContent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(bw);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        logger.info("替换文本成功！结果参见：" + ConfigsUtil.replaceConfig.getDestDir());
        System.out.println("替换文本成功！结果参见：" + ConfigsUtil.replaceConfig.getDestDir());

    }

}
